/*
 * 
 * 
 * 
 */
package com.cms.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;

import com.cms.Feedback;
import com.cms.entity.Config;
import com.cms.entity.Site;
import com.cms.routes.RouteMapping;
import com.cms.util.TemplateUtils;


/**
 * Controller - 站点
 * 
 * 
 * 
 */
@RouteMapping(url = "/admin/site")

public class SiteController extends BaseController {

	/**
	 * 添加
	 */
	public void add() {
	    List<Site> sites = new Site().dao().findList(Site.NEW_TYPE);
	    setAttr("sites", sites);
	    setAttr("templates", TemplateUtils.getTemplates());
	    render(getView("site/add"));
	}

	/**
	 * 保存
	 */
	public void save() {
		Site site = getModel(Site.class,"",true); 
		site.setCreateDate(new Date());
		site.setModifyDate(new Date());
		site.save();
		Site systemSite = new Site().dao().findSystem();
		List<Config> configs = new Config().dao().findList(true, systemSite.getId());
		for(Config config : configs){
		    config.setId(null);
		    config.setSiteId(site.getId());
		    config.setValue(getPara(config.getName()));
		    config.save();
		}
		redirect(getListQuery("/admin/site/list"));
	}

	/**
	 * 编辑
	 */
	public void edit() {
		Long id = getParaToLong("id");
		setAttr("site", new Site().dao().findById(id));
		render(getView("site/edit"));
	}

	/**
	 * 更新
	 */
	public void update() {
		Site site = getModel(Site.class,"",true); 
		site.setModifyDate(new Date());
		site.update();
		redirect(getListQuery("/admin/site/list"));
	}

	/**
	 * 列表
	 */
	public void list() {
	    String name = getPara("name");
		Integer pageNumber = getParaToInt("pageNumber");
		if(pageNumber==null){
			pageNumber = 1;
		}
		setAttr("page", new Site().dao().findPage(name,pageNumber,PAGE_SIZE));
		setAttr("name", name);
		render(getView("site/list"));
	}

	/**
	 * 删除
	 */
	public void delete() {
		Long ids[] = getParaValuesToLong("ids");
		if(ArrayUtils.isNotEmpty(ids)){
			for(Long id:ids){
				new Site().dao().deleteById(id);
			}
		}
		renderJson(Feedback.success(new HashMap<>()));
	}

}